package com.cap.bts.crmdp.dealer.masterinfo.service;

import java.io.File;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.cap.bts.crmdp.commons.sftp.SFTPProcessor;
import com.cap.bts.crmdp.commons.sftp.SftpProperties;
import com.cap.bts.crmdp.dealer.dealerinfosync.dao.IDealerInfoDao;
import com.cap.bts.crmdp.dealer.dealerinfosync.service.IDealerInfoSyncService;
import com.cap.bts.crmdp.dealer.dealerinfosync.util.ProcessCsvFileUtils;
import com.cap.bts.crmdp.dealer.masterdata.domain.MasterDataDealerInfo;
import com.cap.bts.crmdp.dealer.masterdata.dto.MasterDataDealerInfoDto;
import com.cap.bts.crmdp.dealer.masterinfo.dao.IMasterFileDao;
import com.cap.bts.crmdp.dealer.masterinfo.dao.IOtherProductDao;
import com.cap.bts.crmdp.dealer.masterinfo.dao.IServiceInfoDefDao;
import com.cap.bts.crmdp.dealer.purchase.constants.PurchaseConstants;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.service.impl.BaseServiceImpl;
import com.cap.bts.framework.usermgnt.dao.IRoleDao;
import com.cap.bts.framework.usermgnt.dao.IUserDao;
import com.cap.bts.framework.usermgnt.dao.IUserRoleDao;
import com.cap.bts.framework.usermgnt.domain.Organization;
import com.cap.bts.framework.usermgnt.domain.Role;
import com.cap.bts.framework.usermgnt.domain.User;
import com.cap.bts.framework.usermgnt.domain.UserGroup;
import com.cap.bts.framework.usermgnt.domain.UserRole;
import com.cap.bts.framework.usermgnt.util.PasswordUtil;
import com.jcraft.jsch.ChannelSftp;

//@Transactional(rollbackFor = AppException.class)
@Service
public class DealerInfoDataSyncService extends BaseServiceImpl  {

    private static final Logger LOGGER = Logger.getLogger(DealerInfoDataSyncService.class);

    @Autowired
    private ICodeMapping codeMappingService;

    @Autowired
    IOtherProductDao            iOtherProductDao;

    @Autowired
    IServiceInfoDefDao          iServiceInfoDefDao;

    @Autowired
    IMasterFileDao              iMasterFileDao;

    @Autowired
    ICodeMapping                iCodeMapping;
    
    @Autowired
    IDealerInfoSyncService      dealerInfoSyncService;
    
    @Autowired
    IDealerInfoDao dealerInfoDao;
    
    @Autowired
    IUserDao userDao;
    
    @Autowired
    IUserRoleDao userRoleDao;
    
    @Autowired
    IRoleDao roleDao;

    

	public void processSynchronizationDataFromDealerInfo() throws AppException {
		//从SFTP上下载文件
		String sftpInfo = codeMappingService.getCodeValueByCode(PurchaseConstants.SFTP_INFO, PurchaseConstants.DEALERINFODATA);
		SftpProperties sftpProperties = JSON.parseObject(sftpInfo, SftpProperties.class);
		SFTPProcessor ftpUtil = new SFTPProcessor();
        ChannelSftp channelSftp = ftpUtil.getConnect(sftpProperties);
        try {
			if(channelSftp.isConnected()){
				
				//临时目录
				String tmpPath = codeMappingService.getCodeValueByCode("tmpPath", "tmpPath");
				String remoteFile = "Dealerinfo_" + DateFormatUtils.format(new Date(), "yyyy_MM_dd") + ".csv";
				String remote = "Dealerinfo/Dealerinfo_";
				String localFilePath = tmpPath + remote + DateFormatUtils.format(new Date(), "yyyyMMdd_HHmmssSSS");
				String localFile = localFilePath + "/" + remoteFile;
				File file = new File(localFilePath);
				if(!file.exists()){
					file.mkdirs();
				}
				ftpUtil.downloadFile(remoteFile, sftpProperties.getPath(), localFile);
				//处理下载文件
				List<MasterDataDealerInfoDto> dataList = ProcessCsvFileUtils.combinationDealerInfoList(ProcessCsvFileUtils.analyzeCsv(new File(localFile),"UTF-8"));
				if(dataList != null && !dataList.isEmpty()){
					for(int i=0;i<dataList.size();i++){
						MasterDataDealerInfoDto dto = dataList.get(i);
						if("门店加入流程中".equals(dto.getDealerStatus())){
							continue;
						}else{
							if(StringUtils.isNotBlank(dto.getDealerNum())){
								MasterDataDealerInfo dealerInfo = dealerInfoSyncService.getDealerInfoByDealerNum(dto.getDealerNum());
								if(dealerInfo != null){
									//更新dealer
									MasterDataDealerInfo masterDataDealerInfo = masterDataDealerInfoForUpdate(dto,dealerInfo);
									dealerInfoDao.update(masterDataDealerInfo);
									//新建或更新ts_common_user的记录，店长与出纳
									//出纳
									updateOrInsertUser(dto.getDealerNum(), dto);
									//店长
									updateOrInsertUser(dto.getDealerNum()+"_admin", dto);
									//添加tr_user_role的记录TR_USER_ROLE
									updateOrInsertUserAndRole(dto);
								}else{
									//新增
									MasterDataDealerInfo masterDataDealerInfo = masterDataDealerInfoForInsert(dto);
									dealerInfoDao.save(masterDataDealerInfo);
									//添加tr_user_role的记录TR_USER_ROLE
									updateOrInsertUserAndRole(dto);
								}
							}
						}
					}
					//调用存储过程来修改相关信息
					dealerInfoDao.callPrcDealerInfoModify();
				}
			}
		} catch (Exception e) {
			LOGGER.error("processSynchronizationDataFromDealerInfo Error:" + e , e);
		}
	}
	
	public MasterDataDealerInfo masterDataDealerInfoForInsert(MasterDataDealerInfoDto dto) throws AppException {
		MasterDataDealerInfo masterDataDealerInfo = new MasterDataDealerInfo();
		if(StringUtils.isNoneBlank(dto.getDealerNum())){
			try {
				masterDataDealerInfo.setId(Long.parseLong(dto.getDealerNum()));
			} catch (NumberFormatException e) {
				LOGGER.error("masterDataDealerInfoForInsert ERROR" + e , e);
			}
		}
		masterDataDealerInfo.setDealerNum(dto.getDealerNum());
		masterDataDealerInfo.setDealerName(dto.getDealerName());
		masterDataDealerInfo.setAddress(dto.getAddress());
		masterDataDealerInfo.setZipCode(dto.getZipCode());
		masterDataDealerInfo.setRegisteredAddress(dto.getRegisteredAddress());
		masterDataDealerInfo.setOwner(dto.getOwner());
		masterDataDealerInfo.setContact(dto.getContact());
		masterDataDealerInfo.setContactName(dto.getContactName());
		masterDataDealerInfo.setContactPhone(dto.getContactPhone());
		masterDataDealerInfo.setTelephone(dto.getTelephone());
		masterDataDealerInfo.setProvinceName(dto.getProvinceName());
		masterDataDealerInfo.setCityName(dto.getCityName());
		masterDataDealerInfo.setCounty(dto.getCounty());
		masterDataDealerInfo.setRegion(dto.getRegion());
		masterDataDealerInfo.setRegionCode(dto.getRegionCode());
		masterDataDealerInfo.setRegionConsultantMgr(dto.getRegionConsultantMgr());
		masterDataDealerInfo.setConsultant(dto.getConsultant());
		masterDataDealerInfo.setConsultantPhone(dto.getConsultantPhone());
		masterDataDealerInfo.setConsultantMail(dto.getConsultantMail());
		masterDataDealerInfo.setSalesRepresentative(dto.getSalesRepresentative());
		masterDataDealerInfo.setWorkstations(dto.getWorkstations());
		masterDataDealerInfo.setIfHq(dto.getIfHq());
		masterDataDealerInfo.setIfBranch(dto.getIfBranch());
		masterDataDealerInfo.setHqId(dto.getHqId());
		masterDataDealerInfo.setProgramStartDate(dto.getProgramStartDate());
		masterDataDealerInfo.setLongitude(dto.getLongitude());
		masterDataDealerInfo.setLatitude(dto.getLatitude());
		masterDataDealerInfo.setBusinessHours(dto.getBusinessHours());
		masterDataDealerInfo.setDealerStatus(dto.getDealerStatus());
		masterDataDealerInfo.setStatus(dto.getStatus());
		masterDataDealerInfo.setIfDirectPos(dto.getIfDirectPos());
		masterDataDealerInfo.setRiskWaringLevel(dto.getRiskWaringLevel());
		masterDataDealerInfo.setOwnerMobilePhone(dto.getOwnerMobilePhone());
		masterDataDealerInfo.setOwnerIdNumber(dto.getOwnerIdNumber());
		masterDataDealerInfo.setConsultantNum(dto.getConsultantNum());
		masterDataDealerInfo.setExitPlan(dto.getExitPlan());
		masterDataDealerInfo.setExitDealerTypeStatus(dto.getExitDealerTypeStatus());
		masterDataDealerInfo.setFullName(dto.getFullName());
		masterDataDealerInfo.setShortName(dto.getShortName());
		masterDataDealerInfo.setExitDate(dto.getExitDate());
		return masterDataDealerInfo;
	}
	
	public MasterDataDealerInfo masterDataDealerInfoForUpdate(MasterDataDealerInfoDto dto,MasterDataDealerInfo dealerInfo) throws AppException {
		dealerInfo.setDealerNum(dto.getDealerNum());
		dealerInfo.setDealerName(dto.getDealerName());
		dealerInfo.setAddress(dto.getAddress());
		dealerInfo.setZipCode(dto.getZipCode());
		dealerInfo.setRegisteredAddress(dto.getRegisteredAddress());
		dealerInfo.setOwner(dto.getOwner());
		dealerInfo.setContact(dto.getContact());
		dealerInfo.setContactName(dto.getContactName());
		dealerInfo.setContactPhone(dto.getContactPhone());
		dealerInfo.setTelephone(dto.getTelephone());
		dealerInfo.setProvinceName(dto.getProvinceName());
		dealerInfo.setCityName(dto.getCityName());
		dealerInfo.setCounty(dto.getCounty());
		dealerInfo.setRegion(dto.getRegion());
		dealerInfo.setRegionCode(dto.getRegionCode());
		dealerInfo.setRegionConsultantMgr(dto.getRegionConsultantMgr());
		dealerInfo.setConsultant(dto.getConsultant());
		dealerInfo.setConsultantPhone(dto.getConsultantPhone());
		dealerInfo.setConsultantMail(dto.getConsultantMail());
		dealerInfo.setSalesRepresentative(dto.getSalesRepresentative());
		dealerInfo.setWorkstations(dto.getWorkstations());
		dealerInfo.setIfHq(dto.getIfHq());
		dealerInfo.setIfBranch(dto.getIfBranch());
		dealerInfo.setHqId(dto.getHqId());
		dealerInfo.setProgramStartDate(dto.getProgramStartDate());
		dealerInfo.setLongitude(dto.getLongitude());
		dealerInfo.setLatitude(dto.getLatitude());
		dealerInfo.setBusinessHours(dto.getBusinessHours());
		dealerInfo.setDealerStatus(dto.getDealerStatus());
		dealerInfo.setStatus(dto.getStatus());
		dealerInfo.setIfDirectPos(dto.getIfDirectPos());
		dealerInfo.setRiskWaringLevel(dto.getRiskWaringLevel());
		dealerInfo.setOwnerMobilePhone(dto.getOwnerMobilePhone());
		dealerInfo.setOwnerIdNumber(dto.getOwnerIdNumber());
		dealerInfo.setConsultantNum(dto.getConsultantNum());
		dealerInfo.setExitPlan(dto.getExitPlan());
		dealerInfo.setExitDealerTypeStatus(dto.getExitDealerTypeStatus());
		dealerInfo.setFullName(dto.getFullName());
		dealerInfo.setShortName(dto.getShortName());
		dealerInfo.setExitDate(dto.getExitDate());
		return dealerInfo;
	}
	
	public void updateOrInsertUser(String userCodeOrAdmin,MasterDataDealerInfoDto dto) throws AppException{
		try {
			User user = userDao.getUserByUserCode(userCodeOrAdmin);
			if(user != null){
				//更新
				user.setName(dto.getDealerName());
				user.setPassword(PasswordUtil.encodePassword(dto.getConsultantPhone()));
				if("退出".equals(dto.getDealerStatus())){
					user.setIsLocked(1);
				}
				userDao.update(user);
			}else{
				//新增
				User userNew = new User();
				userNew.setUserCode(userCodeOrAdmin);
				userNew.setName(dto.getDealerName());
				userNew.setPassword(PasswordUtil.encodePassword(dto.getConsultantPhone()));
				userNew.setStatusCode(1);
				UserGroup userGroup = new UserGroup();
				userGroup.setId(Long.parseLong("1"));
				userNew.setUserGroup(userGroup);
				Organization organization = new Organization();
				organization.setId(Long.parseLong("3"));
				userNew.setEmployerOrg(organization);
				userNew.setUserType(2);
				userNew.setBrandId(1);
				userNew.setLastLoginTime(new Date());
				userNew.setIsLocked(0);
				userNew.setLoginFailedTimes(0);
				userNew.setEmployeeId(1);
				userNew.setLastPwdChangeTime(new Date());
				userNew.setDealerId(Long.parseLong(dto.getDealerNum()));
				userDao.save(userNew);
			}
		} catch (Exception e) {
			LOGGER.error("updateOrInsertUser Error" + e);
		}
	}

	public void insertRole(User user, Role role) throws AppException{
		UserRole userRole = new UserRole();
		userRole.setUser(user);
		userRole.setRole(role);
		userRole.setIsDefaultRole(0);
		userRoleDao.save(userRole);
	}
	public void updateOrInsertUserAndRole(MasterDataDealerInfoDto dto) throws AppException{
		try {
			//获取user_id
			User user = userDao.getUserByUserCode(dto.getDealerNum());
			User userAdmin = userDao.getUserByUserCode(dto.getDealerNum()+"_admin");
			//获取role_id
			Role cashier = roleDao.getRoleByCode("CASHIER");
			Role shopkeeper = roleDao.getRoleByCode("SHOPKEEPER");
			//查询tr_user_role中是否存在该记录
			if(user != null && userAdmin != null && cashier != null && shopkeeper != null){
				if(!userRoleDao.isExists(user.getId(), cashier.getId())){
					insertRole(user, cashier);
				}
				if(!userRoleDao.isExists(userAdmin.getId(), shopkeeper.getId())){
					insertRole(userAdmin, shopkeeper);
				}
			}
		} catch (Exception e) {
			LOGGER.error("updateOrInsertUserAndRole_Error" + e);
		}
	}
}
